import os, sys, re

class FndRep:
    def __init__(self, src, dest, filere):
        self.src = src
        self.dest = dest
        self.filere = filere
        self.ignorepattern = re.compile(".*\.hg.*")
        
    def matches(self, pattern, str):
        matched = pattern.match(str)
        return matched and matched.group(0) == str
        
    
    def rec(self, f):
        if self.matches(self.ignorepattern, f):
            return
        if os.path.isfile(f):
            #sys.stdout.write(f + "\n")
            buf = open(f, "r").read()
            bufCh = buf.replace(self.src, self.dest)
            if bufCh != buf:
                sys.stdout.write(f)
                sys.stdout.write("\n")
                out = open(f, "w")
                out.write(bufCh)
                out.close()
        if os.path.isdir(f):
            for s in os.listdir(f):
                self.rec(os.path.join(f, s));

if __name__ == "__main__":
    src = sys.argv[1]
    dest = sys.argv[2]
    root = "."
    if len(sys.argv) > 3:
        sys.argv[3]
    filere = ".*"
    if len(sys.argv) > 4:
        filere = sys.argv[4]
    filere = re.compile(filere)
    fr = FndRep(src, dest, filere)
    fr.rec(root)
    
